package com.dog.basics.netty.business.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dog.basics.bean.model.common.DogAppVersionInfo;
import com.dog.basics.common.properties.FileProperties;
import com.dog.basics.common.util.ByteUtil;
import com.dog.basics.common.util.SpringContextUtils;
import com.dog.basics.netty.business.IBusinessServer;
import com.dog.basics.netty.protobuf.dto.DogNewsContentDto;
import com.dog.basics.service.common.IDogAppVersionInfoService;
import com.google.protobuf.ByteString;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.log4j.Log4j2;
import java.io.BufferedInputStream;
import java.util.List;

/**
 * @description: 获取固件升级请求文件消息
 * @author: He
 * @date: Created in 2020/10/9 9:59
 * @version: 1.0
 * @modified By:
 */
@Log4j2
public class ResponseHandlerImplFirmwareFile implements IBusinessServer<DogNewsContentDto.Message> {

    /**
     * @功能描述: 执行.固件请求文件
     * @author He
     * @date 2020/10/9
     */
    @Override
    public void businessHandler(ChannelHandlerContext ctx, DogNewsContentDto.Message msg) throws InterruptedException {
        log.info("获取固件升级文件请求消息:{}", msg.toString());
        // 查询是否那个固件 - 文件
        List<DogAppVersionInfo> appVersionInfos = SpringContextUtils.getBean(IDogAppVersionInfoService.class)
                .list(Wrappers.<DogAppVersionInfo>lambdaQuery().eq(DogAppVersionInfo::getAppType,3).eq(StrUtil.isNotBlank(msg.getImeiVersion()), DogAppVersionInfo::getVersionCode, msg.getImeiVersion()).orderByDesc(DogAppVersionInfo::getCreateTime));
        // 判断是否有文件
        if (CollUtil.isEmpty(appVersionInfos)) {
            closeFirmwareFile(ctx, msg);
            return;
        }
        DogAppVersionInfo appVersionInfo = appVersionInfos.get(0);
        // 获取数据信息
        FileProperties properties = SpringContextUtils.getBean(FileProperties.class);
        BufferedInputStream inputStream = FileUtil.getInputStream(StrUtil.format("{}{}{}", properties.getPath(), properties.getPathname(), appVersionInfo.getApkWrap()));
        // 判断没有文件流 - 跳转失败
        if (ObjectUtil.isNull(inputStream)) {
            closeFirmwareFile(ctx, msg);
            return;
        }
        // 文件转义Bytes
        byte[] bytes = IoUtil.readBytes(inputStream);
        // 判断是否 - 字节流
        if (bytes.length <= 0) {
            closeFirmwareFile(ctx, msg);
            return;
        }
        // 文件字 节分包  - (size 每包大小多少)
        byte[][] bytesData = ByteUtil.splitBytes(bytes, 512);
        // 判断文件包是否大于当前获取的包序列
        if (bytesData.length < msg.getFrameNumber()) {
            closeFirmwareFile(ctx, msg);
            return;
        }
        // 执行返回并且成功
        ctx.channel().writeAndFlush(DogNewsContentDto.Message.newBuilder().setMsgType(msg.getMsgType()).setMsgCode(1)
                .setImeiVersion(appVersionInfo.getVersionCode())
                .setFrameNumber(msg.getFrameNumber())
                .setTotalFrame(bytesData.length)
                .setFirmSize(bytes.length)
                .setFirmDataBytes(ByteString.copyFrom(bytesData[msg.getFrameNumber() - 1]))
        );
    }

    /**
     * 失败的固件请求
     *
     * @param ctx
     * @param msg
     */
    public void closeFirmwareFile(ChannelHandlerContext ctx, DogNewsContentDto.Message msg) {
        ctx.channel().writeAndFlush(DogNewsContentDto.Message.newBuilder().setMsgType(msg.getMsgType()).setMsgCode(2));
        ctx.channel().close();
    }

}